<template>
  <section>
    <div>
      <el-form
        ref="infoForm"
        :model="infoForm"
        :rules="rules"
        label-width="120px"
      >
        <!-- 分类选择 -->
        <el-form-item label="分类" prop="bcategory">
          <el-select v-model="thisbcategory" filterable clearable>
            <el-option
              v-for="item in blogNodeinfoForm"
              :key="item.bID"
              :label="item.btitle"
              :value="item.btitle"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 父导航选择 -->
        <el-form-item label="二级分类
        " prop="bparentId">
          <el-select
            v-model="boxFather.btitle"
            filterable
            clearable
            @visible-change="handleSelectVisibleChange"
            @change="handleSelectChange"
          >
            <el-option
              v-for="item in blogFatherinfoForm"
              :key="item.bID"
              :label="item.btitle"
              :value="item.btitle"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-button type="primary" @click.native="addSubmit">查找</el-button>
      <el-button type="primary" @click.native="addOrder">保存时序</el-button>
    </div>

    <!-- 列表 -->
    <el-table
  :data="ProductList"
  style="width: 100%"
  ref="table"
  class="custom-tbl"
>
  <el-table-column type="selection" width="50"> </el-table-column>
  <el-table-column prop="order" label="时序" width="80">
    <template slot-scope="scope">
      <el-input v-model.number="scope.row.order" 
      :maxlength="3" 
      />
    </template>
  </el-table-column>
  <el-table-column prop="ID" label="ID" width="100" sortable> </el-table-column>
  <el-table-column prop="btitle" label="标题" sortable> </el-table-column>
  <el-table-column prop="bCreateTime" label="创建时间" width="250" sortable> </el-table-column>
</el-table>
  </section>
</template>
<script>
import Toolbar from "../../components/Toolbar";
import {
  getBlogDeatil,
  GetSubBlog,
  GetBlogNode,
  UpdateProductList,
} from "../../api/api";

export default {
  components: { Toolbar },
  data() {
    return {
      users: [],
      ProductList: [], // 新的对象列表,
      total: 0,
      page: 1,
      buttonSubit: "提交按钮",
      initialValue: "",
      submitting: false,
      id: this.$route.params.id,
      infoForm: {
        btitle: "",
        bsubmitter: "",
        bcategory: "技术博文",
        bcontent: "",
        bstarLevel: null,
        bRemark: "",
        StarList: [],
        bstarList: "",
        bparentId: 0,
        Father: {
          bID: 0,
          btitle: "",
        },
        imageUrlList: [],
        bstarList: "",
        bnodeLevel: 0,
      },
      blogNodeinfoForm: [],
      thisbcategory: null,
      blogFatherinfoForm: [],
      boxFather: {},
      dataform: [],
      newstarlist: [],
      bimage: "",
      images: [],
      editorOption: {},
      //表单验证
      rules: {
        btitle: [{ required: true, message: "请输入标题", trigger: "blur" }],
        bcontent: [
          { required: true, message: "请输入详细内容", trigger: "blur" },
        ],
      },
    };
  },

  mounted() {
    //获取一级节点（类型）
    var bcategorynull = { bcategory: null };
    GetBlogNode(bcategorynull).then((res) => {
      this.blogNodeinfoForm = res.data.response;
    });
  },

  methods: {
    addSubmit() {
      console.log( this.boxFather.bID);
      if(this.boxFather.bID==undefined||this.boxFather.bID==null){
        alert("请选择详细分类")
        return;
      }
      let para = {
        level: 3,
        category: this.boxFather.bID,
      };
      this.listLoading = true;

      GetSubBlog(para).then((res) => {
      // 获取数据后，创建一个新的对象列表，其中包含初始时序值
      this.users = res.data.response;

      // 创建新的对象列表
      this.ProductList = this.users.map((item, index) => {
        return {
          ID: item.bID,
          btitle: item.btitle,
          bCreateTime: item.bCreateTime,
          order: index + 1  // 设置初始的时序值
        };
      });
      this.listLoading = false;
    });
  },


  addOrder() {
          console.log(this.ProductList)
    if(this.ProductList==null||this.ProductList.length==0){
      alert("没有数据 无法更新时序");
      return
    };
  // 将所有的 order 值转换为字符串形式，然后检查唯一性
  const orderValues = this.ProductList.map(item => String(item.order));
  const uniqueOrders = new Set(orderValues);

  if (uniqueOrders.size !== orderValues.length) {
    alert("存在重复的时序值，请修改后再保存。");
  } else {

    // 如果没有重复时序值，执行保存操作
    UpdateProductList(this.ProductList).then((res) => {
      if (res.data.success) {
        this.$notify({
          type: "success",
          message: "修改成功!",
          duration: 3000,
        });
        this.addSubmit();

      } else {
        this.submitting = false;
        var errorMsg = res.data.msg;
        this.$message({
          type: "error",
          message: errorMsg,
          showClose: true,
        });
      }
    });

    // 这里执行保存操作，保存修改后的对象列表
    console.log('保存成功:', this.users);
  }
},
    ///下拉框所有节点"all""
    handleSelectStart(visible) {
      if (visible) {
        if (true) {
          var bcategorythis = { bcategory: "ALL" };
          GetBlogNode(bcategorythis)
            .then((res) => {
              if (res.data && res.data.response) {
                this.blogFatherinfoForm = res.data.response;
              }
            })
            .catch((error) => {});
        }
      }
    },

    //所有该分类节点
    handleSelectVisibleChange(visible) {
      if (visible) {
        if (this.thisbcategory) {
          var bcategorythis = { bcategory: this.thisbcategory };
          GetBlogNode(bcategorythis)
            .then((res) => {
              if (res.data && res.data.response) {
                this.blogFatherinfoForm = res.data.response;
              }
            })
            .catch((error) => {
              console.error("Failed to get blogFatherinfoForm:", error);
            });
        }
      }
    },

    // 在下拉框选项改变时更新boxFather为选中的对象
    handleSelectChange(value) {
      if (this.blogFatherinfoForm && this.blogFatherinfoForm.length > 0) {
        this.blogFatherinfoForm.forEach((item) => {
          if (item.btitle === value) {
            this.boxFather = item;
            this.infoForm.bnodeLevel = item.bnodeLevel + 1;
          }
        });
      }
    },
  },
};
</script>

<style scoped>
.custom-tbl /deep/ .has-gutter .el-checkbox {
  display: none;
}
</style>
